package com.library.admin.listener;

import books.storage.service.BookDto;
import books.storage.service.EntityNotFoundException_Exception;
import books.storage.service.NotEnoughtExemplaireException_Exception;

import com.library.admin.AdmLibrary;
import com.library.admin.form.UpdateExemplariesNumberForm;
import com.library.admin.manager.BookManagerPanel;
import com.library.admin.service.LibraryService;
import com.vaadin.ui.Button.ClickEvent;
import com.vaadin.ui.Button.ClickListener;
import com.vaadin.ui.Window.Notification;

public class UpdateExemplariesNumberListener implements ClickListener {
	private static final long serialVersionUID = 1L;
	
	private String bookIsbn;
	private UpdateExemplariesNumberForm updateExemplariesNumberForm;

	public UpdateExemplariesNumberListener(UpdateExemplariesNumberForm updateExemplariesNumberForm, String bookIsbn) {
		this.bookIsbn = bookIsbn;
		this.updateExemplariesNumberForm = updateExemplariesNumberForm;
	}

	public void buttonClick(ClickEvent event) {
		if (updateExemplariesNumberForm.isValid()) {
			AdmLibrary libraryApplication = (AdmLibrary) event.getComponent().getApplication();
			try {
				BookDto bookToModify = LibraryService.getServiceBook().findBook(bookIsbn);
				String exemplariesNumber = updateExemplariesNumberForm.getNumberTextField().getValue().toString();
				if (exemplariesNumber.startsWith("-")) {
					int remove = Integer.valueOf(exemplariesNumber.substring(1, exemplariesNumber.length()));
					LibraryService.getServiceBook().removeCopies(remove, bookToModify);
					libraryApplication.getMainWindow().showNotification(remove + " exemplaires ont étés supprimés.", Notification.TYPE_HUMANIZED_MESSAGE);
				}
				else {
					int add = Integer.valueOf(exemplariesNumber);
					LibraryService.getServiceBook().addCopies(add, bookToModify);
					libraryApplication.getMainWindow().showNotification(add + " exemplaires ont étés ajoutés.", Notification.TYPE_HUMANIZED_MESSAGE);
				}
				BookManagerPanel bookManagerPanel = (BookManagerPanel) libraryApplication.getMainPanel().getComponent(0);
				bookManagerPanel.getBookTable().updateBookTable();
				bookManagerPanel.getBookTable().requestRepaint();
				
			}
			catch (EntityNotFoundException_Exception e) {
				libraryApplication.getMainWindow().showNotification("Impossible d'ajouter ou supprimer des exemplaires.", Notification.TYPE_ERROR_MESSAGE);
				e.printStackTrace();
			}
			catch (NotEnoughtExemplaireException_Exception e) {
				e.printStackTrace();
			}
		}
	}
}
